package br.com.localfloripa.services;

import java.util.Collection;

import javax.inject.Inject;
import javax.inject.Named;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import br.com.localfloripa.dao.UsuarioDao;
import br.com.localfloripa.entities.Usuario;

@Service("jpaUserDetailsService")
@Scope("singleton")
public class JpaUserDetailsService extends ServiceMain implements UserDetailsService {
	
	private static final long serialVersionUID = 6743416278908451096L;
	private static final Logger log = LoggerFactory.getLogger(JpaUserDetailsService.class);

	@Inject
	@Named("usuarioDao")
	private UsuarioDao usuarioDao;
	
	@Override
	public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException, DataAccessException {
		
		Usuario usuario = null;
		try {
			usuario = usuarioDao.findByLogin(login);
			if (usuario == null)
				throw new UsernameNotFoundException(bundle.getString("manager.security.login.notfound"));
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			throw new UsernameNotFoundException(e.getMessage());
		}		
		return usuario;
	}

	public UsuarioDao getUsuarioDao() {
		return usuarioDao;
	}

	public void setUsuarioDao(UsuarioDao usuarioDao) {
		this.usuarioDao = usuarioDao;
	}
	
	public Usuario getLoggedUser() throws Exception {
		
		Usuario loggedUser = null;
		Authentication authentication = (Authentication) SecurityContextHolder.getContext().getAuthentication();
		if (authentication != null) {
			Object obj = authentication.getPrincipal();
			if (obj instanceof Usuario) {
				loggedUser = (Usuario) obj;
			}
		}
		return loggedUser;		
	}
	
	public Boolean isAdminUser() throws Exception {
		
		Boolean isAdmin = false;
		Authentication authentication = (Authentication) SecurityContextHolder.getContext().getAuthentication();
		Collection<GrantedAuthority> authorities = authentication.getAuthorities();
		for (GrantedAuthority authority : authorities) {
			if (authority.getAuthority().equals("ADMIN")) {
				isAdmin = true;
				break;
			}
		}
		return isAdmin;		
	}
	

}
